<template>
  <div class="BlogToc-container">
    <h2>目录</h2>
    <RightList :list="tocWithSelect" @select="handleSelect" />
  </div>
</template>

<script>
import RightList from "./RightList";
export default {
  props: {
    toc: {
      type: Array,
    },
  },
  components: { RightList },
  data: () => ({
    activeAnchor: "",
  }),
  computed: {
    // 根据toc属性和Anchor得到带有isSelect的数据
    tocWithSelect() {
      const getToc = (toc = []) => {
        return toc.map((t) => ({
          ...t,
          isSelect: t.anchor === this.activeAnchor,
          children: getToc(t.children),
        }));
      };
      return getToc(this.toc);
    },
    // 根据toc获取元素数组
    doms() {
      const doms = [];
      const addToDoms = (toc = []) => {
        toc.forEach((t) => {
          doms.push(document.getElementById(t.anchor));
          t.children && t.children.length && addToDoms(t.children);
        });
      };
      addToDoms(this.toc);
      return doms;
    },
  },
  created() {
    this.$bus.$on("mainScroll", this.setSelect);
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.setSelect);
  },
  methods: {
    handleSelect(item) {
      location.hash = item.anchor;
    },
    setSelect(scrolDom) {
      if (!scrolDom) return;
      const rang = 200;
      for (const dom of this.doms) {
        if (!dom) continue;

        //距离视口头部200px以内 选中
        const top = dom.getBoundingClientRect().top;
        if (top >= 0 && top <= rang) {
          // 在范围内
          this.activeAnchor = dom.id;
          return;
        } else if (top > rang) {
          // 在范围下
          return;
        } else {
          // 在范围上
          this.activeAnchor = dom.id; // 先假设自己激活的，然后继续看后面
        }
      }
      //   this.activeAnchor = anchor;
    },
  },
};
</script>

<style lang='less' scoped>
</style>
